const db = wx.cloud.database()
const _ = db.command
var app = getApp()
Page({

    data: {
		matchId:null,
		teamData:{},
		buttonData:"新建组队",
		typeData: ["创新创业", "艺术", "体育", "计算机", "学科","其他"],
        typeIndex: 0,
        titleCount: 0,
        titleCountOut: "silver",
        needCount: 0,
        needCountOut: "silver",
        areaData: [
            ["全国"],
            ["全省"],
            ["全市"]
        ],
        area: "全国",
        areaIndex: [0, 0, 0],
		lasttime:0//防抖
    },
	newTeam(e) {
		// 防抖
		let d = new Date();
		let nowtime = d.getTime();//获取点击时间
		if (nowtime - this.data.lasttime < 1500) {//1500ms内return
			console.log("!!!")
			return
		}
		this.setData({
			lasttime: nowtime
		})
		////////提交
		// console.log(e.detail.value)
		let teamData = e.detail.value
		if (this.data.titleCountOut == "red" || this.data.needCountOut == "red") {
			wx.showToast({
				title: '存在字数超额',
				icon: 'none',
				duration: 1500
			})
			return
		}
		for (let key in teamData) {
			if (typeof (teamData[key]) == "string" && teamData[key].replace(/\s+/g, '') == '') {//信息不能为空
				wx.showToast({
					title: '信息都不能为空',
					icon: 'none',
					duration: 1500
				})
				return
			}
		}
		teamData.area = this.data.area
		teamData.type = this.data.typeData[teamData.type]
		//更新操作
		// console.log(this.data.team_id)
		if (this.data.teamId != undefined){
			// let data = this.data.teamData
			// delete data._id
			db.collection("team").doc(this.data.team_id).update({
				data: teamData
			}).then(res=>{
				wx.showToast({
					title: '保存成功', // 标题
					icon: 'success',
					// 图标类型，默认success
					duration: 1500  // 提示窗停留时间，默认1500ms
				})
				}).catch(err=>{
					console.log(err)
					wx.showToast({
						title: '保存失败', // 标题
						icon: 'none',
						// 图标类型，默认success
						duration: 1500  // 提示窗停留时间，默认1500ms
					})
				})
		}else{
			//新建操作
			teamData["status"] = true
			teamData["beinvited"] = []
			teamData["teamPeople"] = [app.globalData.openid]
			if(this.data.matchId != null){
				teamData["aboutMatchId"] = [this.data.matchId]
			}
			teamData["teamId"] = app.globalData.openid + "@" + new Date().getTime()
			console.log(teamData)
			db.collection("team").add({ data: teamData }).then(
				wx.showToast({
					title: '新建成功', // 标题
					icon: 'success',
					// 图标类型，默认success
					duration: 1500  // 提示窗停留时间，默认1500ms
				}),
				setTimeout(function () {
					wx.navigateBack({
						data: 1
					})
				}, 500)
			).catch(err=>{
				wx.showToast({
					title: '新建失败', // 标题
					icon: 'none',
					// 图标类型，默认success
					duration: 1500  // 提示窗停留时间，默认1500ms
				})
		})
		}
	},
    typeChange(e) {
        console.log(e)
        this.setData({
            typeIndex: e.detail.value
        })
    },
    //组队区域设置
    areaColumnChange(e) {
		// console.log(e)
		let column = e.detail.column
		let index = e.detail.value
		//all
		if (column == 0 && index == 0){
			let area1 = "areaData[1]"
			let area2 = "areaData[2]"
			this.setData({
				[area1]: ["全省"],
				[area2]: ["全市"],
				areaIndex:[0,0,0]
			})
		}
		if (column == 1 && index == 0) {
			let areaData = "areaData[2]"
			let areaIndex = "areaIndex[2]"
			let areaIndex1 = "areaIndex[1]"
			this.setData({
				[areaIndex1]:0,
				[areaIndex]: 0,
				[areaData]:["全市"]
			})
		}
		//1
		if (column == 0&&index != 0){
				wx.cloud.callFunction({
					name:"getCities",
					data:{
						province: this.data.areaData[0][index]
					}
				}).then(res => {
				// console.log(res)
				let data = res.result.data[0].cities
				// console.log(data)
				let citys = ["全省"]
				for (let i = 0; i < data.length; i++) {
					citys.push(data[i].city_name)
					// console.log(data[i])
				}
				console.log(citys)
				let citysData = "areaData[1]"
				let collegesData = "areaData[2]"
				this.setData({
					[citysData]: citys,
					areaIndex:[index,0,0],
					[collegesData]:["全市"]
				})
			})
		}	
		//2
		if (column == 1 && index != 0) {
			wx.cloud.callFunction({
				name:"getCities",
				data:{
					province: this.data.areaData[0][this.data.areaIndex[0]]
				}
			}).then(res => {
				// console.log(res)
				// console.log(this.data.areaData[1][index])
				let data = res.result.data[0].cities
				// console.log(data)
				let colleges = ["全市"]
				for (let i = 0; i < data.length; i++) {
					console.log(data[i].city_name )
					if (data[i].city_name == this.data.areaData[1][index]){
						colleges = colleges.concat(data[i].universities)
						break
					}
					// console.log(this.data.areaData[1][index])
					// console.log(data[i])
				}
				console.log(colleges)
				let collegesData = "areaData[2]"
				let areaIndex1 = "areaIndex[1]"
				let areaIndex2 = "areaIndex[2]"
				this.setData({
					[collegesData]: colleges,
					[areaIndex1]:index,
					[areaIndex2]:0
				})
			})
		}	
    },
    areaChange(e) {
        let indexArr = e.detail.value
        this.setData({
            areaIndex: indexArr
        })
        if (indexArr[0] == 0) {
            this.setData({
                area: this.data.areaData[0][0]
            })
        } else if (indexArr[1] == 0) {
            this.setData({
                area: this.data.areaData[0][indexArr[0]]
            })
        } else if (indexArr[2] == 0) {
            this.setData({
				area: this.data.areaData[1][indexArr[1]]
            })
        } else {
            this.setData({
                area: this.data.areaData[2][indexArr[2]]
            })
        }
    },
    //标题字数控制
    titleInput(e) {
        console.log(e.detail.value.length)
        if (e.detail.value.length > 10) {
            this.setData({
                titleCountOut: "red"
            })
        } else {
            this.setData({
                titleCountOut: "silver"
            })
        }
        this.setData({
            titleCount: e.detail.value.length
        })
    },
    //需求字数控制
    needInput(e) {
        console.log(e.detail.value.length)
        if (e.detail.value.length > 7) {
            this.setData({
                needCountOut: "red"
            })
        } else {
            this.setData({
                needCountOut: "silver"
            })
        }
        this.setData({
            needCount: e.detail.value.length
        })
    },
	/**
	* 生命周期函数--监听页面加载
	*/
	onLoad: function (options) {
		console.log(options.matchId )
		//传入相关赛事id
		if(options.matchId != undefined){
			this.setData({
				matchId: options.matchId 
			})
			console.log(this.data.matchId)
		}
		// options.teamId = "teamId"
		//判断是更新还是新建
		if (options.teamId != undefined ){
			this.setData({
				teamId: options.teamId,
				buttonData:"保存"
			})
		}
		// 准备pick函数
		wx.cloud.callFunction({
			name: "getProvinces"
		}).then(res => {
			let data = res.result.data
			console.log(data)
			let provinces = []
			for (let i = 0; i < data.length; i++) {
				provinces.push(data[i].province_name)
			}
			console.log(provinces)
			let provinceData = "areaData[0]"
			this.setData({
				[provinceData]: ["全国"].concat(provinces)
			})
		})
	},
      /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function() {		
		//当前为更新时加载数据
		if (this.data.teamId != undefined) {
			db.collection("team").where({
				teamId: this.data.teamId 
			}).field({
				title:true,
				type:true,
				area:true,
				need:true,
				needDetail:true,
				teamMassage:true,
				other:true
			}).get().then(res=>{
				// console.log(res.data[0])
				let data = res.data[0]
				for(let key in this.data.typeData){
					if (this.data.typeData[key] == data.type){
						this.setData({
							typeIndex:key
						})
					}
				}
				this.setData({
					teamData :data,
					area:data.area,
					team_id:data._id
				})
			})
			///
		}
    },
})